package cn.didi.feidi.androidorder.fragment.personal;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.personal.PersonFindBackPayPasswordGuideActivity;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.assembly.FeiDiInputPasswordFragmentDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.MoneyUserLog;
import cn.didi.feidi.androidorder.util.MD5Util;

/**
 * 提现
 */
public class PersonToCashFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonToCashFragment";

    private EditText aliPayAccount;
    private EditText personTrueName;
    private EditText toCashValues;

    private TextView commitTv;


    private String toCashMoney;
    private String account;
    private String realName;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonToCashFragment newInstance(Bundle bundle) {
        PersonToCashFragment fragment = new PersonToCashFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_to_cash, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }


    @Override
    protected void initViews(View rootView) {
        aliPayAccount = (EditText) rootView.findViewById(R.id.person_to_cash_edit_ali_pay_account);
        personTrueName = (EditText) rootView.findViewById(R.id.person_to_cash_edit_person_true_name);

        toCashValues = (EditText) rootView.findViewById(R.id.person_to_cash_edit_money);
        commitTv = (TextView) rootView.findViewById(R.id.person_to_cash_commit_tv);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addListener() {
        commitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                account = aliPayAccount.getText().toString().trim();
                realName = personTrueName.getText().toString().trim();
                toCashMoney = toCashValues.getText().toString().trim();

                if (account == null || "".equals(account)) {
                    makeToast("账号不能为空");
                    return;
                }

                if (realName == null || "".equals(realName)) {
                    makeToast("姓名不能为空");
                    return;
                }

                if (toCashMoney == null || "".equals(toCashMoney)) {
                    makeToast("输入金额不能为空");
                    return;
                }

                if (Float.parseFloat(toCashMoney) <= 0) {
                    makeToast("输入金额必须大于零");
                    return;
                }

                if (Float.parseFloat(toCashMoney) > UserManager.getMoney()) {
                    makeToast("输入金额不能大于" + UserManager.getMoney());
                    return;
                }

                //支付密码输入框
                final FeiDiInputPasswordFragmentDialog inputPasswordFragmentDialog = new FeiDiInputPasswordFragmentDialog();

                inputPasswordFragmentDialog.setCallback(new FeiDiInputPasswordFragmentDialog.Callback() {
                    @Override
                    public void inputCallback(String inputString) {
                        //输入完 6 位密码后自动回调 发起支付
                        toCashRequest(inputPasswordFragmentDialog,inputString);
                    }
                }).setForgetPassworListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //忘记密码
                        Intent intent = new Intent(getContext(), PersonFindBackPayPasswordGuideActivity.class);
                        startActivity(intent);
                    }
                });
                inputPasswordFragmentDialog.show(getChildFragmentManager(), "personToCashFragment");


            }
        });
        /**
         * 限定2位小数
         */
        toCashValues.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        toCashValues.setText(s);
                        toCashValues.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    toCashValues.setText(s);
                    toCashValues.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        toCashValues.setText(s.subSequence(0, 1));
                        toCashValues.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    private void toCashRequest(final FeiDiInputPasswordFragmentDialog inputPasswordFragmentDialog, String payPassword) {
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("amount", toCashMoney);
        params.put("realName", realName);
        params.put("way", String.valueOf(2));
        params.put("account", account);
        params.put("payPwd", MD5Util.GetMD5Code32Bit(payPassword));

        executeRequest(new AppActionRequest<MoneyUserLog>(Api.MONEY_USER_WITHDRAW_DEPOSIT, params,
                new TypeToken<ApiResponse<MoneyUserLog>>() {
                }.getType(), new ActionCallbackListener<MoneyUserLog>() {
            @Override
            public void onSuccess(String message, MoneyUserLog data) {
                if (data != null) {
                    UserManager.setMoney(data.getBalance());
                    makeToast("提现成功");
                    getActivity().finish();
                }
                inputPasswordFragmentDialog.dismiss();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                switch (errorEvent) {
                    case ErrorEvent.WRONG_PAYPWD:
//                      支付密码错误
                        makeToast(message);
                        inputPasswordFragmentDialog.clearInput();
                        break;
                    case ErrorEvent.DRAW_NUM_LIMIT:
                        makeToast("提现已达上限");
                        inputPasswordFragmentDialog.dismiss();
                        break;
                    case ErrorEvent.FEIDI_WALLET_PAY_PASSWORD_BEYOND_FIVE_TIME_IN_ONE_HOUR:
                        new CommomDialog(getContext(), R.style.dialog, "密码错误次数已达上限\n请一小时后重试", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm){
                                    dialog.dismiss();
                                    inputPasswordFragmentDialog.dismiss();
                                }
                            }
                        },true,true).setPositiveButton("好的").show();
                        break;
                    default:
                        makeToast("请输入正确的账号和名字");
                        inputPasswordFragmentDialog.dismiss();
                        break;
                }
            }
        }));
    }
}
